using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Framework;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.UI.UserControls;
using HeroldIT.Dnn.Modules.WebControls;

namespace HeroldIT.Dnn.Modules.News.Views
{
    public class Edit : PortalModuleBase, INewsSatelliteModuleSettingsProvider
    {
        #region constants

        private static readonly string KeyNewsEntry = typeof (Edit) + "_NewsEntry";

        #endregion

        #region control fields

        protected ITextControl txtDisplayDate;
        protected ITextControl txtPublishOn;
        protected ITextControl txtPublishUntil;
        protected ITextControl txtDisplayOrder;
        protected ListControl lstCategories;
        protected ITextControl txtNewCategory;
        protected IButtonControl btnNewCategory;
        protected ICheckBoxControl chkIsSticky;
        protected ICheckBoxControl chkIsHidden;
        protected ListControl lstLocale;
        protected IButtonControl btnDeleteLocale;
        protected ITextControl txtHeadline;
        protected ITextControl txtSubline;
        protected ITextControl txtTeaserText;
        protected ITextControl txtTeaserImageUrl;
        protected ITextControl txtTeaserImageCaption;
        protected Control ctlTeaserImageUrl2Container;
        protected Control ctlTeaserImageCaption2Container;
        protected ITextControl txtTeaserImageUrl2;
        protected ITextControl txtTeaserImageCaption2;
        protected Control ctlTeaserImageUrl3Container;
        protected Control ctlTeaserImageCaption3Container;
        protected ITextControl txtTeaserImageUrl3;
        protected ITextControl txtTeaserImageCaption3;
        protected Control ctlTeaserImageUrl4Container;
        protected Control ctlTeaserImageCaption4Container;
        protected ITextControl txtTeaserImageUrl4;
        protected ITextControl txtTeaserImageCaption4;
        protected ITextControl txtSource;
        protected ITextControl txtDetailText;
        protected ITextControl txtDetailImageUrl;
        protected ICheckBoxControl chkUseDetailImageForTeaser;
        protected ITextControl txtDetailImageCaption;
        protected Control ctlDetailImageUrl2Container;
        protected Control ctlDetailImageCaption2Container;
        protected ITextControl txtDetailImageUrl2;
        protected ITextControl txtDetailImageCaption2;
        protected Control ctlDetailImageUrl3Container;
        protected Control ctlDetailImageCaption3Container;
        protected ITextControl txtDetailImageUrl3;
        protected ITextControl txtDetailImageCaption3;
        protected Control ctlDetailImageUrl4Container;
        protected Control ctlDetailImageCaption4Container;
        protected ITextControl txtDetailImageUrl4;
        protected ITextControl txtDetailImageCaption4;
        protected UrlControl urlDetailUrl;
        protected URLTrackingControl utcDetailUrl;
        protected ICheckBoxControl chkLocaleIsHidden;
        protected ICheckBoxControl chkIsDefaultLocale;
        protected IButtonControl btnUpdate;
        protected IButtonControl btnCancel;
        protected IButtonControl btnDelete;

        #endregion

        #region properties

        private NewsController controller;

        private NewsController Controller
        {
            get { return this.controller ?? (this.controller = new NewsController(this)); }
        }

        protected string EditingLocale { get; set; }

        protected NewsEntry NewsEntry
        {
            get
            {
                NewsEntry entry = null;
                if (this.IsPostBack)
                {
                    entry = this.Session[KeyNewsEntry] as NewsEntry;
                }
                else
                {
                    string entryIdValue = this.Request.QueryString["EntryId"];
                    if (!String.IsNullOrEmpty(entryIdValue))
                    {
                        int entryId;
                        if (int.TryParse(entryIdValue, NumberStyles.None, CultureInfo.InvariantCulture, out entryId))
                        {
                            entry = this.Controller.ReadNewsEntry(entryId);
                            this.Session[KeyNewsEntry] = entry;
                        }
                    }
                }
                if (null == entry)
                {
                    entry = new NewsEntry();
                    entry.Details.CreatingNewsEntryDetail += (sender,args) => args.Argument.UseDetailImageForTeaser = this.Controller.GetUseDetailImageForTeaser();
                    this.Session[KeyNewsEntry] = entry;
                }
                return entry;
            }
        }

        protected virtual string FilledLocaleSuffix
        {
            get { return " (*)"; }
        }

        private bool hasCategories;

        protected bool HasCategories
        {
            get
            {
                if (!this.hasCategories)
                {
                    IList<string> categories = this.Controller.GetCategories();
                    this.hasCategories = null != categories && categories.Count > 0;
                }
                return this.hasCategories;
            }
        }

        protected LocaleCollection DisplayLocales
        {
            get
            {
                return this.ShowDisabledLanguages
                           ? Localization.GetSupportedLocales()
                           : Localization.GetEnabledLocales();
            }
        }

        protected bool ShowDisabledLanguages
        {
            get { return this.controller.GetShowDisabledLanguages(); }
        }

        protected int MaxImagesToUse
        {
            get { return this.controller.GetMaxImagesToUse(); }
        }

        #endregion

        #region page lifecycle

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Page.RegisterRequiresControlState(this);

            if (null != this.btnUpdate)
            {
                this.btnUpdate.Click += this.btnUpdate_Click;
            }

            if (null != this.btnCancel)
            {
                this.btnCancel.Click += this.btnCancel_Click;
            }

            if (null != this.btnDelete)
            {
                Control ctlDelete = this.btnDelete as Control;
                if (null != ctlDelete && this.NewsEntry.NewsEntryId <= 0)
                {
                    ctlDelete.Visible = false;
                }

                this.btnDelete.Click += this.btnDelete_Click;
            }
            if (!this.IsPostBack)
            {
                if (null != this.lstCategories)
                {
                    this.lstCategories.DataSource = this.Controller.GetCategories();
                    this.lstCategories.DataBind();
                }
            }
            if (null != this.btnNewCategory)
            {
                this.btnNewCategory.Click += this.btnNewCategory_Click;
            }
            new[] {this.txtTeaserImageUrl, this.txtTeaserImageUrl2, this.txtTeaserImageUrl3, this.txtTeaserImageUrl4}
                .OfType<ImageBrowser>()
                .All(ib =>
                         {
                             ib.MaxImageWidth = this.Controller.GetMaxTeaserImageWidth();
                             ib.MaxImageHeight = this.Controller.GetMaxTeaserImageHeight();
                             ib.ImageQuality = (int)this.Controller.GetTeaserImageQuality();
                             ib.MatteColor = this.Controller.GetTeaserImageMatte();
                             ib.InitialFolder = this.Controller.MakeFolderUrl(this.Controller.GetTeaserImageFolder());
                             return true;
                         });
            new[] {this.txtDetailImageUrl, this.txtDetailImageUrl2, this.txtDetailImageUrl3, this.txtDetailImageUrl4}
                .OfType<ImageBrowser>()
                .All(ib =>
                         {
                             ib.MaxImageWidth = this.Controller.GetMaxDetailImageWidth();
                             ib.MaxImageHeight = this.Controller.GetMaxDetailImageHeight();
                             ib.ImageQuality = (int) this.Controller.GetDetailImageQuality();
                             ib.MatteColor = this.Controller.GetDetailImageMatte();
                             ib.InitialFolder = this.Controller.MakeFolderUrl(this.Controller.GetDetailImageFolder());
                             return true;
                         });

            if (null != this.lstLocale)
            {
                this.lstLocale.SelectedIndexChanged += this.lstLocale_SelectedIndexChanged;

                LocaleCollection displayLocales = this.DisplayLocales;
                foreach (Locale locale in displayLocales.AllValues)
                {
                    int index = locale.Text.IndexOf(" (");
                    this.lstLocale.Items.Add(new ListItem((index >= 0 ? locale.Text.Substring(0, index) : locale.Text) + (this.NewsEntry.Details.Contains(locale.Code) ? this.FilledLocaleSuffix : ""), locale.Code));
                }

                if (!this.IsPostBack)
                {
                    this.EditingLocale = ((PageBase)this.Page).PageCulture.Name;
                    if (!this.NewsEntry.Details.Contains(this.EditingLocale))
                    {
                        this.EditingLocale = this.NewsEntry.Details.GetDefaultDetail(this.Controller.GetDefaultLocale()).Locale;
                    }
                    var item = this.lstLocale.Items.FindByValue(this.EditingLocale);
                    if (null == item)
                    {
                        var firstLocale = this.lstLocale.Items[0];
                        this.EditingLocale = firstLocale.Value;
                        firstLocale.Selected = true;
                    }
                    else
                    {
                        item.Selected = true;
                    }
                    this.LoadValues();
                }
            }
            if (null != this.btnDeleteLocale)
            {
                this.btnDeleteLocale.Click += this.btnDeleteLocale_Click;
            }
        }

        protected override void LoadControlState(object savedState)
        {
            Pair pair = savedState as Pair;
            if (null != pair)
            {
                if (pair.Second is string)
                {
                    this.EditingLocale = (string) pair.Second;
                }
                base.LoadControlState(pair.First);
            }
            else if (savedState is string)
            {
                this.EditingLocale = (string) savedState;
            }
            else
            {
                base.LoadControlState(savedState);
            }
        }

        protected override object SaveControlState()
        {
            object controlState = base.SaveControlState();

            if (null != controlState)
            {
                return new Pair(controlState, this.EditingLocale);
            }
            return this.EditingLocale;
        }

        #endregion

        #region event handlers

        private void lstLocale_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.UpdateLocaleValues();
            this.EditingLocale = this.lstLocale.SelectedValue;
            this.LoadLocaleValues();
        }

        private void btnDeleteLocale_Click(object sender, EventArgs e)
        {
            this.DeleteLocale();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            this.UpdateEntry();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.CancelUpdate();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            this.DeleteEntry();
        }

        void btnNewCategory_Click(object sender, EventArgs e)
        {
            if (null != this.txtNewCategory && !String.IsNullOrEmpty(this.txtNewCategory.Text)
                && !this.txtNewCategory.Text.Contains(";") && null != this.lstCategories)
            {
                int index =
                    Array.BinarySearch(this.lstCategories.Items.Cast<ListItem>().Select(li => li.Value).ToArray(),
                                       this.txtNewCategory.Text);
                if (index < 0)
                {
                    ListItem item = new ListItem(this.txtNewCategory.Text) {Selected = true};
                    this.lstCategories.Items.Insert(~index, item);
                    this.hasCategories = true;
                }
                else
                {
                    this.lstCategories.Items[~index].Selected = true;
                }
                this.txtNewCategory.Text = "";
            }
        }

        #endregion

        #region methods

        /// <summary>
        /// Gets the localized string for the given key.
        /// </summary>
        /// <param name="key">The key for which to find the localized string.</param>
        /// <returns>The localized string for the given key.</returns>
        protected string GetString(string key)
        {
            return Localization.GetString(key, this.LocalResourceFile);
        }

        protected void UpdateLocaleList()
        {
            if (null != this.lstLocale)
            for (int i = 0; i < this.lstLocale.Items.Count; i++)
            {
                ListItem locale = this.lstLocale.Items[i];
                if (this.NewsEntry.Details.Contains(locale.Value))
                {
                    if (!locale.Text.EndsWith(this.FilledLocaleSuffix))
                    {
                        locale.Text += this.FilledLocaleSuffix;
                    }
                }
                else
                {
                    if (locale.Text.EndsWith(this.FilledLocaleSuffix))
                    {
                        locale.Text = locale.Text.Substring(0, locale.Text.Length - this.FilledLocaleSuffix.Length);
                    }
                }
            }
        }

        protected virtual void UpdateValues()
        {
            this.NewsEntry.ModuleId = this.ModuleId;

            if (null != this.lstCategories)
            {
                this.NewsEntry.Categories = String.Join(";", (this.lstCategories.Items
                                                                 .Cast<ListItem>()
                                                                 .Where(item => item.Selected)
                                                                 .Select(item => item.Value))
                                                                 .ToArray());
            }
            if (null != this.txtDisplayDate)
            {
                this.NewsEntry.DisplayDate = DateTime.Parse(this.txtDisplayDate.Text, CultureInfo.CurrentUICulture);
            }
            if (null != this.txtPublishOn)
            {
                this.NewsEntry.PublishOn = String.IsNullOrEmpty(this.txtPublishOn.Text)
                                               ? null
                                               : (DateTime?)
                                                 DateTime.Parse(this.txtPublishOn.Text, CultureInfo.CurrentUICulture);
            }
            if (null != this.txtPublishUntil)
            {
                this.NewsEntry.PublishUntil = String.IsNullOrEmpty(this.txtPublishUntil.Text)
                                                  ? null
                                                  : (DateTime?)
                                                    DateTime.Parse(this.txtPublishUntil.Text,
                                                                   CultureInfo.CurrentUICulture);
            }
            if (null != this.txtDisplayOrder)
            {
                int displayOrder;
                if (int.TryParse(this.txtDisplayOrder.Text, NumberStyles.Integer,
                                                        CultureInfo.CurrentUICulture, out displayOrder))
                {
                    this.NewsEntry.DisplayOrder = displayOrder;
                }
            }
            if (null != this.chkIsSticky)
            {
                this.NewsEntry.IsSticky = this.chkIsSticky.Checked;
            }
            if (null != this.chkIsHidden)
            {
                this.NewsEntry.IsHidden = this.chkIsHidden.Checked;
            }
            this.UpdateLocaleValues();

            this.NewsEntry.Headline = this.NewsEntry.Details.Count > 0
                                          ? this.NewsEntry.Details[0].Headline
                                          : String.Empty;
        }

        protected virtual void UpdateLocaleValues()
        {
            NewsEntryDetail detail = this.NewsEntry.Details[this.EditingLocale];
            if (null != this.txtHeadline)
            {
                detail.Headline = this.txtHeadline.Text;
            }
            if (null != this.txtSubline)
            {
                detail.Subline = this.txtSubline.Text;
            }
            if (null != this.txtTeaserText)
            {
                detail.TeaserText = this.txtTeaserText.Text;
            }
            if (null != this.txtTeaserImageUrl)
            {
                detail.TeaserImageUrl = this.txtTeaserImageUrl.Text;
            }
            if (null != this.txtTeaserImageCaption)
            {
                detail.TeaserImageCaption = this.txtTeaserImageCaption.Text;
            }
            if (null != this.txtTeaserImageUrl2)
            {
                detail.TeaserImageUrl2 = this.txtTeaserImageUrl2.Text;
            }
            if (null != this.txtTeaserImageCaption2)
            {
                detail.TeaserImageCaption2 = this.txtTeaserImageCaption2.Text;
            }
            if (null != this.txtTeaserImageUrl3)
            {
                detail.TeaserImageUrl3 = this.txtTeaserImageUrl3.Text;
            }
            if (null != this.txtTeaserImageCaption3)
            {
                detail.TeaserImageCaption3 = this.txtTeaserImageCaption3.Text;
            }
            if (null != this.txtTeaserImageUrl4)
            {
                detail.TeaserImageUrl4 = this.txtTeaserImageUrl4.Text;
            }
            if (null != this.txtTeaserImageCaption4)
            {
                detail.TeaserImageCaption4 = this.txtTeaserImageCaption4.Text;
            }
            if (null != this.txtDetailText)
            {
                detail.DetailText = this.txtDetailText.Text;
            }
            if (null != this.chkUseDetailImageForTeaser)
            {
                detail.UseDetailImageForTeaser = this.chkUseDetailImageForTeaser.Checked;
            }
            if (null != this.txtDetailImageUrl)
            {
                detail.DetailImageUrl = this.txtDetailImageUrl.Text;
            }
            if (null != this.txtDetailImageCaption)
            {
                detail.DetailImageCaption = this.txtDetailImageCaption.Text;
            }
            if (null != this.txtDetailImageUrl2)
            {
                detail.DetailImageUrl2 = this.txtDetailImageUrl2.Text;
            }
            if (null != this.txtDetailImageCaption2)
            {
                detail.DetailImageCaption2 = this.txtDetailImageCaption2.Text;
            }
            if (null != this.txtDetailImageUrl3)
            {
                detail.DetailImageUrl3 = this.txtDetailImageUrl3.Text;
            }
            if (null != this.txtDetailImageCaption3)
            {
                detail.DetailImageCaption3 = this.txtDetailImageCaption3.Text;
            }
            if (null != this.txtDetailImageUrl4)
            {
                detail.DetailImageUrl4 = this.txtDetailImageUrl4.Text;
            }
            if (null != this.txtDetailImageCaption4)
            {
                detail.DetailImageCaption4 = this.txtDetailImageCaption4.Text;
            }
            if (null != this.urlDetailUrl)
            {
                detail.DetailUrl = this.urlDetailUrl.Url;
            }
            if (null != this.txtSource)
            {
                detail.Source = this.txtSource.Text;
            }
            if (null != this.chkLocaleIsHidden)
            {
                detail.IsHidden = this.chkLocaleIsHidden.Checked;
            }
            if (null != this.chkIsDefaultLocale)
            {
                detail.IsDefaultLocale = this.chkIsDefaultLocale.Checked;
            }
            if (detail.IsEmpty())
            {
                this.NewsEntry.Details.Remove(this.EditingLocale);
            }
            this.UpdateLocaleList();
        }

        protected virtual void LoadValues()
        {
            if (null != this.lstCategories && !String.IsNullOrEmpty(this.NewsEntry.Categories))
            {
                foreach (string category in this.NewsEntry.Categories.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries))
                {
                    ListItem item = this.lstCategories.Items.FindByValue(category);
                    //if (null != item)
                    //{
                        item.Selected = true;
                    //}
                }
            }
            if (null != this.txtDisplayDate)
            {
                this.txtDisplayDate.Text = this.NewsEntry.DisplayDate.ToString("d", CultureInfo.CurrentUICulture);
            }
            if (null != this.txtPublishOn)
            {
                this.txtPublishOn.Text = this.NewsEntry.PublishOn.HasValue
                                             ? this.NewsEntry.PublishOn.Value.ToString("d", CultureInfo.CurrentUICulture)
                                             : String.Empty;
            }
            if (null != this.txtPublishUntil)
            {
                this.txtPublishUntil.Text = this.NewsEntry.PublishUntil.HasValue
                                                ? this.NewsEntry.PublishUntil.Value.ToString("d",
                                                                                             CultureInfo.
                                                                                                 CurrentUICulture)
                                                : String.Empty;
            }
            if (null != this.txtDisplayOrder)
            {
                this.txtDisplayOrder.Text = this.NewsEntry.DisplayOrder.ToString(CultureInfo.CurrentUICulture);
            }
            if (null != this.chkIsSticky)
            {
                this.chkIsSticky.Checked = this.NewsEntry.IsSticky;
            }
            if (null != this.chkIsHidden)
            {
                this.chkIsHidden.Checked = this.NewsEntry.IsHidden;
            }
            this.LoadLocaleValues();
        }

        protected virtual void LoadLocaleValues()
        {
            NewsEntryDetail detail = this.NewsEntry.Details[this.EditingLocale];
            if (null != this.txtHeadline)
            {
                this.txtHeadline.Text = detail.Headline ?? String.Empty;
            }
            if (null != this.txtSubline)
            {
                this.txtSubline.Text = detail.Subline ?? String.Empty;
            }
            if (null != this.txtTeaserText)
            {
                this.txtTeaserText.Text = detail.TeaserText ?? String.Empty;
            }
            if (null != this.txtTeaserImageUrl)
            {
                try
                {
                    this.txtTeaserImageUrl.Text = detail.TeaserImageUrl;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtTeaserImageUrl.Text = null;
                }
            }
            if (null != this.txtTeaserImageCaption)
            {
                this.txtTeaserImageCaption.Text = detail.TeaserImageCaption;
            }
            if (null != this.txtDetailText)
            {
                this.txtDetailText.Text = detail.DetailText ?? String.Empty;
            }
            if (null != this.txtDetailImageUrl)
            {
                try
                {
                    this.txtDetailImageUrl.Text = detail.DetailImageUrl;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtDetailImageUrl.Text = null;
                }
            }
            if (null != this.chkUseDetailImageForTeaser)
            {
                this.chkUseDetailImageForTeaser.Checked = detail.UseDetailImageForTeaser;
            }
            if (null != this.txtDetailImageCaption)
            {
                this.txtDetailImageCaption.Text = detail.DetailImageCaption;
            }
            if (null != this.txtTeaserImageUrl2)
            {
                try
                {
                    this.txtTeaserImageUrl2.Text = detail.TeaserImageUrl2;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtTeaserImageUrl2.Text = null;
                }
            }
            if (null != this.txtTeaserImageCaption2)
            {
                this.txtTeaserImageCaption2.Text = detail.TeaserImageCaption2;
            }
            if (null != this.txtDetailImageUrl2)
            {
                try
                {
                    this.txtDetailImageUrl2.Text = detail.DetailImageUrl2;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtDetailImageUrl2.Text = null;
                }
            }
            if (null != this.txtDetailImageCaption2)
            {
                this.txtDetailImageCaption2.Text = detail.DetailImageCaption2;
            }
            if (null != this.txtTeaserImageUrl3)
            {
                try
                {
                    this.txtTeaserImageUrl3.Text = detail.TeaserImageUrl3;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtTeaserImageUrl3.Text = null;
                }
            }
            if (null != this.txtTeaserImageCaption3)
            {
                this.txtTeaserImageCaption3.Text = detail.TeaserImageCaption3;
            }
            if (null != this.txtDetailImageUrl3)
            {
                try
                {
                    this.txtDetailImageUrl3.Text = detail.DetailImageUrl3;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtDetailImageUrl3.Text = null;
                }
            }
            if (null != this.txtDetailImageCaption3)
            {
                this.txtDetailImageCaption3.Text = detail.DetailImageCaption3;
            }
            if (null != this.txtTeaserImageUrl4)
            {
                try
                {
                    this.txtTeaserImageUrl4.Text = detail.TeaserImageUrl4;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtTeaserImageUrl4.Text = null;
                }
            }
            if (null != this.txtTeaserImageCaption4)
            {
                this.txtTeaserImageCaption4.Text = detail.TeaserImageCaption4;
            }
            if (null != this.txtDetailImageUrl4)
            {
                try
                {
                    this.txtDetailImageUrl4.Text = detail.DetailImageUrl4;
                }
                catch (ArgumentException ae)
                {
                    Exceptions.LogException(ae);
                    this.txtDetailImageUrl4.Text = null;
                }
            }
            if (null != this.txtDetailImageCaption4)
            {
                this.txtDetailImageCaption4.Text = detail.DetailImageCaption4;
            }
            if (null != this.urlDetailUrl)
            {
                this.urlDetailUrl.Url = detail.DetailUrl;
            }
            if (null != this.utcDetailUrl)
            {
                if (detail.NewsEntryDetailId > 0 && !String.IsNullOrEmpty(detail.DetailUrl))
                {
                    this.utcDetailUrl.URL = detail.DetailUrl;
                    this.utcDetailUrl.ModuleID = this.ModuleId;
                    this.utcDetailUrl.Visible = true;
                }
                else
                {
                    this.utcDetailUrl.Visible = false;
                }
            }
            if (null != this.txtSource)
            {
                this.txtSource.Text = detail.Source;
            }
            if (null != this.chkLocaleIsHidden)
            {
                this.chkLocaleIsHidden.Checked = detail.IsHidden;
            }
            if (null != this.chkIsDefaultLocale)
            {
                this.chkIsDefaultLocale.Checked = detail.IsDefaultLocale;
            }
            var cntnrs = new[]
                             {
                                 this.ctlTeaserImageUrl4Container, this.ctlTeaserImageCaption4Container,
                                 this.ctlDetailImageUrl4Container, this.ctlDetailImageCaption4Container,
                                 this.ctlTeaserImageUrl3Container, this.ctlTeaserImageCaption3Container,
                                 this.ctlDetailImageUrl3Container, this.ctlDetailImageCaption3Container,
                                 this.ctlTeaserImageUrl2Container, this.ctlTeaserImageCaption2Container,
                                 this.ctlDetailImageUrl2Container, this.ctlDetailImageCaption2Container,
                             };
            int maxImageUsed =
                (!String.IsNullOrEmpty(detail.TeaserImageUrl4) || !String.IsNullOrEmpty(detail.TeaserImageCaption4) || !String.IsNullOrEmpty(detail.DetailImageUrl4) || !String.IsNullOrEmpty(detail.DetailImageCaption4))
                ? 4
                : (!String.IsNullOrEmpty(detail.TeaserImageUrl3) || !String.IsNullOrEmpty(detail.TeaserImageCaption3) || !String.IsNullOrEmpty(detail.DetailImageUrl3) || !String.IsNullOrEmpty(detail.DetailImageCaption3))
                ? 3
                : (!String.IsNullOrEmpty(detail.TeaserImageUrl2) || !String.IsNullOrEmpty(detail.TeaserImageCaption2) || !String.IsNullOrEmpty(detail.DetailImageUrl2) || !String.IsNullOrEmpty(detail.DetailImageCaption2))
                ? 2
                : 1;
            int maxImagesToShow = Math.Max(maxImageUsed, this.MaxImagesToUse);
            for (int i = 0; i < cntnrs.Length; i++)
            {
                int batch = i / 4;
                bool isTeaser = (i % 4) == 0 || (i % 4) == 1;
                Control container = cntnrs[i];
                if (null != container)
                {
                    container.Visible = (4 - maxImagesToShow <= batch) && (!isTeaser || !this.chkUseDetailImageForTeaser.Checked);
                }
            }
        }

        protected void UpdateEntry()
        {
            this.UpdateValues();

            foreach (NewsEntryDetail detail in this.NewsEntry.Details)
            {
                if (detail.UseDetailImageForTeaser)
                {
                    if (!String.IsNullOrEmpty(detail.DetailImageUrl))
                    {
                        string directory = VirtualPathUtility.GetDirectory(detail.DetailImageUrl);
                        string fileName = VirtualPathUtility.GetFileName(detail.DetailImageUrl);
                        string extension = VirtualPathUtility.GetExtension(detail.DetailImageUrl);
                        string destinationUrl = directory + fileName.Substring(0, fileName.Length - extension.Length)
                                                + ".teaser" + extension;
                        string sourcePath = this.Server.MapPath(detail.DetailImageUrl);
                        string destinationPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".teaser"
                                                 + Path.GetExtension(sourcePath));
                        File.Copy(sourcePath, destinationPath, true);
                        this.Controller.ResizeTeaserImage(destinationUrl);
                        detail.TeaserImageUrl = destinationUrl;
                        detail.TeaserImageCaption = detail.DetailImageCaption;
                    }
                    if (!String.IsNullOrEmpty(detail.DetailImageUrl2))
                    {
                        string directory = VirtualPathUtility.GetDirectory(detail.DetailImageUrl2);
                        string fileName = VirtualPathUtility.GetFileName(detail.DetailImageUrl2);
                        string extension = VirtualPathUtility.GetExtension(detail.DetailImageUrl2);
                        string destinationUrl = directory + fileName.Substring(0, fileName.Length - extension.Length)
                                                + ".teaser" + extension;
                        string sourcePath = this.Server.MapPath(detail.DetailImageUrl2);
                        string destinationPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".teaser"
                                                 + Path.GetExtension(sourcePath));
                        File.Copy(sourcePath, destinationPath, true);
                        this.Controller.ResizeTeaserImage(destinationUrl);
                        detail.TeaserImageUrl2 = destinationUrl;
                        detail.TeaserImageCaption2 = detail.DetailImageCaption2;
                    }
                    if (!String.IsNullOrEmpty(detail.DetailImageUrl3))
                    {
                        string directory = VirtualPathUtility.GetDirectory(detail.DetailImageUrl3);
                        string fileName = VirtualPathUtility.GetFileName(detail.DetailImageUrl3);
                        string extension = VirtualPathUtility.GetExtension(detail.DetailImageUrl3);
                        string destinationUrl = directory + fileName.Substring(0, fileName.Length - extension.Length)
                                                + ".teaser" + extension;
                        string sourcePath = this.Server.MapPath(detail.DetailImageUrl3);
                        string destinationPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".teaser"
                                                 + Path.GetExtension(sourcePath));
                        File.Copy(sourcePath, destinationPath, true);
                        this.Controller.ResizeTeaserImage(destinationUrl);
                        detail.TeaserImageUrl3 = destinationUrl;
                        detail.TeaserImageCaption3 = detail.DetailImageCaption3;
                    }
                    if (!String.IsNullOrEmpty(detail.DetailImageUrl4))
                    {
                        string directory = VirtualPathUtility.GetDirectory(detail.DetailImageUrl4);
                        string fileName = VirtualPathUtility.GetFileName(detail.DetailImageUrl4);
                        string extension = VirtualPathUtility.GetExtension(detail.DetailImageUrl4);
                        string destinationUrl = directory + fileName.Substring(0, fileName.Length - extension.Length)
                                                + ".teaser" + extension;
                        string sourcePath = this.Server.MapPath(detail.DetailImageUrl4);
                        string destinationPath = Path.Combine(Path.GetDirectoryName(sourcePath), Path.GetFileNameWithoutExtension(sourcePath) + ".teaser"
                                                 + Path.GetExtension(sourcePath));
                        File.Copy(sourcePath, destinationPath, true);
                        this.Controller.ResizeTeaserImage(destinationUrl);
                        detail.TeaserImageUrl4 = destinationUrl;
                        detail.TeaserImageCaption4 = detail.DetailImageCaption4;
                    }
                }
            }
            int id = this.Controller.StoreNewsEntry(this.NewsEntry);
            if (null != this.urlDetailUrl)
            {
                new UrlController().UpdateUrl(this.PortalSettings.PortalId, this.urlDetailUrl.Url, this.urlDetailUrl.UrlType, this.urlDetailUrl.Log, this.urlDetailUrl.Track, this.ModuleId, this.urlDetailUrl.NewWindow);
            }
            if (id > 0)
            {
                this.NavigateToList();
            }
        }

        protected void CancelUpdate()
        {
            this.NavigateToList();
        }

        protected void DeleteEntry()
        {
            if (this.NewsEntry.NewsEntryId > 0)
            {
                this.Controller.DeleteNewsEntry(this.NewsEntry.NewsEntryId);
            }
            this.NavigateToList();
        }

        protected void DeleteLocale()
        {
            this.NewsEntry.Details.Remove(this.EditingLocale);
            if (this.NewsEntry.Details.Count > 0)
            {
                this.lstLocale.SelectedValue = this.NewsEntry.Details[0].Locale;
            }
            else
            {
                this.lstLocale.SelectedIndex = 0;
            }
            this.EditingLocale = this.lstLocale.SelectedValue;
            this.LoadLocaleValues();
            this.UpdateLocaleList();
        }

        protected void NavigateToList()
        {
            this.Response.Redirect(Globals.NavigateURL());
        }

        #endregion
    }
}